//
//  StatusPictureView.swift
//  微博三天
//
//  Created by jessica on 15/11/16.
//  Copyright © 2015年 jessica. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

//注册一个 ID
private let PictureCellId = "PictureCellId"

private let PictureCellMargin: CGFloat = 5

class StatusPictureView: UICollectionView{

    
    var imageURLs : [NSURL]? {
    
        didSet{
            //打印一下数据
//        print(imageURLs)
            //刷新数据
           reloadData()
            
            
            let viewSize  = self.calceViewSize()
          //NSURL
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            
            //中间添加视图个数
            textLabel.text = "\(imageURLs?.count ?? 0)"
            
        }
    
    }
//
//    //计算配图的大小,利用小算法,计算
    private func calceViewSize() -> CGSize {
//        //获取配图最大宽度
//        
//        let colum: CGFloat = 3
//
//        //添加一个精度,虽然没有实际意义,但是不兼容6/6s Plus
//        
        let colum : CGFloat = 3.0000000000001
//
        let maxWidth = screenW - 2 * StatusCellMargin
        //单个图片宽度
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        
        //图片
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //设置大小
    layout.itemSize = CGSizeMake( itemWidth, itemWidth )
        
        let imageCount = imageURLs?.count ?? 0
        if imageCount  == 0 {
            return CGSizeZero
        }
        
        //单张图片
        if imageCount == 1 {
            
                  //单张图片处理
//            let imageSize = CGSize(width: 180, height: 120)
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key)
            //添加图片的Size
            let imageSize = image.size
            layout.itemSize = imageSize
            return imageSize
        }
        //2张图片
        if imageCount == 2 {
        
        
        let w = itemWidth * 2 + PictureCellMargin
            return CGSize(width: w, height: itemWidth)
        
        }
        //四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        //多图
        //行
        /*
        1,2,3   -> 1
        4,5,6   -> 2
        7,8,9   -> 3
        */
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = row * itemWidth + (row - 1) * PictureCellMargin
        
        return CGSize(width: w, height: h)
    }

    
    //重写父类方法
    
    init() {
        let layout = UICollectionViewFlowLayout()
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //添加属性
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        
        registerClass(PictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        //设置自己为自己的数据源
        dataSource = self
        
        
        
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置约束
    private func setupUI(){
    
  backgroundColor = UIColor.randomColor()
        
        //添加数字
        addSubview(textLabel)
        //添加约束
        textLabel.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self.snp_center)
        }

    }
    //懒加载控件
    private lazy var textLabel : UILabel = {
    
        let lab = UILabel()
        lab.textColor = UIColor.randomColor()
        lab.font = UIFont.systemFontOfSize(27)
        lab.sizeToFit()
    return lab
    
    }()
    

}


//实现数据源方法

extension StatusPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let  cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureCell
        //        cell.backgroundColor = UIColor.randomColor()
        cell.url = imageURLs![indexPath.item]
        return cell
    }
}

class PictureCell: UICollectionViewCell {
    
    
    var url: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(url, placeholderImage: nil)
        }
    }
    
    //MARK: 3.重写父类的构造方法 调用设置UI
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 2.设置 UI
    
    private func setupUI() {
        //添加子控件
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //MARK: 1. 懒加载所有子控件
//    private lazy var imageView: UIImageView = UIImageView()
    
    private lazy var imageView : UIImageView = {
    
        let iv = UIImageView()
        //设置图片显示样式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        //手写代码 必须自己手动添加 剪裁
        iv.clipsToBounds = true
        return iv
        }()
    
    
}
//
